package org.dromara.product.service.impl;

import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.product.domain.KyProductDetails;
import org.dromara.product.domain.KyStockInRelations;
import org.dromara.product.domain.bo.KyProductDetailsBo;
import org.dromara.product.domain.bo.KyStockInRelationsBo;
import org.dromara.product.mapper.KyProductDetailsMapper;
import org.dromara.product.mapper.KyStockInRelationsMapper;
import org.springframework.stereotype.Service;
import org.dromara.product.domain.bo.KyStockInRecordsBo;
import org.dromara.product.domain.vo.KyStockInRecordsVo;
import org.dromara.product.domain.KyStockInRecords;
import org.dromara.product.mapper.KyStockInRecordsMapper;
import org.dromara.product.service.IKyStockInRecordsService;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 入库记录Service业务层处理
 *
 * @author kuyu
 * @date 2023-12-29
 */
@RequiredArgsConstructor
@Service
public class KyStockInRecordsServiceImpl implements IKyStockInRecordsService {

    private final KyStockInRecordsMapper baseMapper;
    private final KyStockInRelationsMapper relationsMapper;
    private final KyProductDetailsMapper detailsMapper;

    /**
     * 查询入库记录
     */
    @Override
    public KyStockInRecordsVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询入库记录列表
     */
    @Override
    public TableDataInfo<KyStockInRecordsVo> queryPageList(KyStockInRecordsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<KyStockInRecords> lqw = buildQueryWrapper(bo);
        Page<KyStockInRecordsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询入库记录列表
     */
    @Override
    public List<KyStockInRecordsVo> queryList(KyStockInRecordsBo bo) {
        LambdaQueryWrapper<KyStockInRecords> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<KyStockInRecords> buildQueryWrapper(KyStockInRecordsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<KyStockInRecords> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getWarehouseId() != null, KyStockInRecords::getWarehouseId, bo.getWarehouseId());
        lqw.eq(StringUtils.isNotBlank(bo.getStockNo()), KyStockInRecords::getStockNo, bo.getStockNo());
        lqw.eq(bo.getMid() != null, KyStockInRecords::getMid, bo.getMid());
        lqw.eq(StringUtils.isNotBlank(bo.getPlatform()), KyStockInRecords::getPlatform, bo.getPlatform());
        lqw.eq(bo.getInTypeId() != null, KyStockInRecords::getInTypeId, bo.getInTypeId());
        lqw.eq(bo.getSupplyId() != null, KyStockInRecords::getSupplyId, bo.getSupplyId());
        lqw.eq(StringUtils.isNotBlank(bo.getImages()), KyStockInRecords::getImages, bo.getImages());
        lqw.eq(bo.getTransOutId() != null, KyStockInRecords::getTransOutId, bo.getTransOutId());
        lqw.eq(bo.getZoneId() != null, KyStockInRecords::getZoneId, bo.getZoneId());
        lqw.eq(bo.getStatus() != null, KyStockInRecords::getStatus, bo.getStatus());
        lqw.eq(bo.getPrintNum() != null, KyStockInRecords::getPrintNum, bo.getPrintNum());
        lqw.eq(StringUtils.isNotBlank(bo.getRecordInfo()), KyStockInRecords::getRecordInfo, bo.getRecordInfo());
        lqw.eq(StringUtils.isNotBlank(bo.getMark()), KyStockInRecords::getMark, bo.getMark());
        lqw.eq(StringUtils.isNotBlank(bo.getCustom()), KyStockInRecords::getCustom, bo.getCustom());
        lqw.eq(bo.getApproveLevel() != null, KyStockInRecords::getApproveLevel, bo.getApproveLevel());
        lqw.eq(bo.getTransId() != null, KyStockInRecords::getTransId, bo.getTransId());
        lqw.eq(bo.getFromWarehouseId() != null, KyStockInRecords::getFromWarehouseId, bo.getFromWarehouseId());
        lqw.eq(bo.getFromZoneId() != null, KyStockInRecords::getFromZoneId, bo.getFromZoneId());
        return lqw;
    }

    /**
     * 新增入库记录
     */
    @Override
    public Boolean insertByBo(KyStockInRecordsBo bo) {
        System.out.println(bo);
        List<KyStockInRelationsBo> inList = bo.getInList();
        if(inList.size() <= 0){
            return false;
        }
        String oldCode = baseMapper.selectLatestCode();
        bo.setStockNo(setOrderCode(oldCode,"rkd"));
        KyStockInRecords add = MapstructUtils.convert(bo, KyStockInRecords.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            System.out.println(inList);
            //添加入庫單關聯單據
            inList.forEach((item)->{
                copyInfo(bo,item);
                KyStockInRelations data = MapstructUtils.convert(item, KyStockInRelations.class);
                relationsMapper.insert(data);
                //对每个数量添加唯一code
                setProductCode(item);
            });
        }
        return flag;
    }

    //多线程添加溯源码
    public void setProductCode(KyStockInRelationsBo relations){
        KyProductDetailsBo detailsBo = copyInfoToProduct(relations);
        String orderNo = relations.getInRecordNo();
        List<KyProductDetails> detailList = new ArrayList<>();
        for (int i = 0;i<detailsBo.getNumber().intValue();i++){
            String str = String.format("%08d",i+1);
            String code = orderNo+str;
            code = code.replace("rkd","");
            System.out.println(code);
            detailsBo.setCode(code);
            KyProductDetails details = MapstructUtils.convert(detailsBo, KyProductDetails.class);
            detailList.add(details);
        }
        detailsMapper.insertBatch(detailList);
    }


    /**
     * @param number
     * @param type
     * @return
     */
    public String setOrderCode(String number,String type) {
        // 0 代表前面补充0
        // 4 代表长度为4
        // d 代表参数为正数型
        String dateStr =  new SimpleDateFormat("yyyyMMdd").format(new Date());
        int NewNumber = 0;
        if(number != null) {
            String number1 = number.replace(type, "").substring(8);
            System.out.println(number1);
            NewNumber = Integer.parseInt(number1);
        }
        NewNumber++;
        System.out.println(NewNumber);
        return type + dateStr+String.format("%05d", Integer.valueOf(NewNumber));
    }

    /**
     * 属性赋值
     * @param bo
     * @param relationsBo
     */
    public void copyInfo(KyStockInRecordsBo bo,KyStockInRelationsBo relationsBo){
        relationsBo.setInRecordId(bo.getId());
        relationsBo.setInRecordNo(bo.getStockNo());
        relationsBo.setZoneId(bo.getZoneId());
        relationsBo.setWarehouseId(bo.getWarehouseId());
        relationsBo.setInTypeId(bo.getInTypeId());
        relationsBo.setSupplyId(bo.getSupplyId());
    }

    /**
     * 入库关联属性赋值
     * @param relationsBo
     * @return
     */
    public KyProductDetailsBo copyInfoToProduct(KyStockInRelationsBo relationsBo){
        KyProductDetailsBo detailsBo = new KyProductDetailsBo();
        detailsBo.setProductId(relationsBo.getProductId());
        detailsBo.setBatchNo(relationsBo.getBathInNo());
        detailsBo.setWarehouseId(relationsBo.getWarehouseId());
        detailsBo.setZoneId(relationsBo.getZoneId());
        detailsBo.setMgrUsr(relationsBo.getMid().toString());
        detailsBo.setPrice(relationsBo.getPrice());
        detailsBo.setInNo(relationsBo.getInRecordNo());
        detailsBo.setNumber(relationsBo.getNumber());
        return  detailsBo;
    }


    /**
     * 修改入库记录
     */
    @Override
    public Boolean updateByBo(KyStockInRecordsBo bo) {
        KyStockInRecords update = MapstructUtils.convert(bo, KyStockInRecords.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(KyStockInRecords entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除入库记录
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
